package org.example.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class RedisUtil {

    private static final String root = "blog:";

    @Autowired
    private RedisTemplate redisTemplate;

    public <T> void setObject(final String key, final T value, final Integer timeout) {
        redisTemplate.opsForValue().set(root + key, value, timeout, TimeUnit.SECONDS);
    }

    public <T> T getObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(root + key);
    }

    public boolean deleteObject(final String key) {
        return redisTemplate.delete(root + key);
    }

    public int deleteLikeObject(final String key) {
        Set keys = redisTemplate.keys(root + key);
        if (!CollectionUtils.isEmpty(keys)) {
            keys.forEach(item -> redisTemplate.delete(item));
        }
        assert keys != null;
        return keys.size();
    }

}
